package com.weilele.leisure.time


import androidx.annotation.WorkerThread
import com.weilele.leisure.time.bean.AppConfigBean
import com.weilele.leisure.time.bean.LoginInfoBean
import com.weilele.leisure.time.net.ApiInstance
import com.weilele.mvvm.app
import com.weilele.mvvm.base.livedata.createStatusLiveData
import com.weilele.mvvm.base.livedata.data
import com.weilele.mvvm.setMvvmLibOnCreateOkHttpListener
import com.weilele.mvvm.utils.activity.getUtdId
import com.weilele.mvvm.utils.activity.readAssetsFileFromJson
import com.weilele.mvvm.utils.file.kvDecode
import com.weilele.mvvm.utils.file.kvEncode
import okhttp3.Interceptor
import okhttp3.Response

object CommonHttp {
    init {
        initOkHttp()
    }

    /**
     * 用户信息
     */
    val userInfo by lazy { createStatusLiveData<LoginInfoBean>() }

    /**
     * qpp默认配置
     */
    private lateinit var appConfigBean: AppConfigBean
    val BASE_URL: String
        get() = appConfigBean.hiddenurls + "/"
    val BASE_URL_2: String
        get() = appConfigBean.websiteurl + "/"
    val homePages: MutableList<AppConfigBean.VideocfgDTO.NavsDTO>
        get() = appConfigBean.videocfg.navs

    private const val KEY_LOGIN_INFO = "KEY_LOGIN_INFO"

    /**
     * 加载默认配置并且登录
     */
    @WorkerThread
    suspend fun loadAppConfigAndLogin(): LoginInfoBean {
        appConfigBean = app.readAssetsFileFromJson<AppConfigBean>("app_config.json")!!
        var result = LoginInfoBean()
        val saveInfo = kvDecode(KEY_LOGIN_INFO, result)
        if (saveInfo == result) {
            result = ApiInstance.preregist().result
            kvEncode(KEY_LOGIN_INFO, result)
        } else {
            result = saveInfo
        }
        return result
    }

    private fun initOkHttp() {
        setMvvmLibOnCreateOkHttpListener {
            it.addInterceptor {
                addHeadInterceptor(it)
            }
        }
    }

    /**
     * 统一请求头拦截器
     */
    private fun addHeadInterceptor(chain: Interceptor.Chain): Response {
        val token = userInfo.data?.token ?: ""
        val request = chain.request().newBuilder()
        request.addHeader("device", getUtdId() ?: "")
        request.addHeader("stoken", appConfigBean.stoken)
        request.addHeader("token", token)
        request.addHeader("secret", appConfigBean.secret)
        request.addHeader("v", "128")
        request.addHeader("User-Agent", "okhttp/3.11.0")
        return chain.proceed(request.build())
    }
}